import { Http, Headers, Response,Jsonp, RequestOptions, URLSearchParams } from '@angular/http';
import 'rxjs/add/operator/toPromise';

import { Injectable } from '@angular/core';

import { Trip } from './trip';
import { SERVER } from '../../app.config';

@Injectable()
export class TripService {
    constructor(private http: Http){

    }

    getTrips(): Promise<Trip[]> {
        return this.http.get(SERVER.TRIP)
        .toPromise()
        .then(response => response.json().trip as Trip[])
        .catch(this.handleError);
    }

    getTripsByCarrierID(): Promise<Trip[]>{
        let headers = new Headers();
        headers.append('Content-Type', 'application/json');
        let url = `${SERVER.TRIP}` + '/carrier/' + localStorage.getItem('loginUsercarrierID');
        return this.http.get(url,{ headers: headers})
          .toPromise()
          .then(response => response.json().trip as Trip[])
          .catch(this.handleError);
    }

    getTrip(trip_id: number) {
        return this.getTrips()
            .then(trips => trips.find(trip => trip.trip_id ===trip_id ));
    }

    private handleError(error: any): Promise<any> {
        console.error('错误：', error);

        return Promise.reject(error.message || error);
    }

    //添加
    private post(trip: Trip): Promise<Trip> {
        let headers = new Headers({
            'Content-type': 'application/json'});

        return this.http.post(SERVER.TRIP, JSON.stringify(trip), {headers: headers})
        .toPromise()
        .then(res => res.json().data)
        .catch(this.handleError);
    }

    //更新
    private put(trip: Trip): Promise<Trip> {
        let headers = new Headers();
        headers.append('Content-Type', 'application/json');

        let url = `${SERVER.TRIP}` + '/' + trip.trip_id;

        return this.http.put(url, JSON.stringify(trip), {headers: headers})
                   .toPromise()
                   .then(() => trip)
                   .catch(this.handleError);
    }

    //删除
    delete(trip: Trip): Promise<Response> {
        let headers = new Headers();
        headers.append('Content-Type', 'application/json');

        let url = `${SERVER.TRIP}/${trip.trip_id}`;

        return this.http
                   .delete(url, { headers: headers})
                   .toPromise()
                   .catch(this.handleError);
    }

    //保存
    save(trip: Trip): Promise<Trip> {
        if (trip.trip_id) {
            return this.put(trip)
        }
        return this.post(trip);
    }
}
